﻿#include "VideoReScaler.h"


extern "C"
{
#include "libavcodec/avcodec.h"
#include "libswscale/swscale.h"
#include "libavutil/avutil.h"
}

VideoReScaler::VideoReScaler()
{
}

//像素格式转换
void VideoReScaler::Init(int inWidth, int inHeight, int inPixFmt,int outWidth, int outHeight, int outPixFmt)
{
	std::unique_lock<std::mutex>lock(mMutex);
	this->inWidth_ = inWidth;
	this->inHeight_ = inHeight;
	this->outWidth_ = outWidth;
	this->outHeight_ = outHeight;
	swsCtx = sws_getCachedContext(swsCtx,
		inWidth, inHeight, (AVPixelFormat) inPixFmt,//输入的宽高及像素格式
		outWidth, outHeight,//输出的宽高
		(AVPixelFormat)outPixFmt,//输出的像素格式
		SWS_BILINEAR,//双线性插值算法
		0, 0, 0
	);
	if (!swsCtx)
	{
		qDebug() << "sws_getCachedContext failed!";
	}
}

void VideoReScaler::StartScale(AVFrame* frame)
{
	std::unique_lock<std::mutex>lock(mMutex);
	int ret = sws_scale(swsCtx
		, frame->data, frame->linesize, 0, frame->height,
		frame->data, frame->linesize
	);
	if (ret <= 0)
	{
		PrintError(ret, "StartScale");
	}
}
void VideoReScaler::Release()
{
	if (swsCtx)
	{
		sws_freeContext(swsCtx);
		swsCtx = nullptr;
	}
}
void VideoReScaler::PrintError(int err, QString msg)
{
	if (err < 0)
	{
		char buf[1024] = { 0 };
		av_strerror(err, buf, sizeof(buf) - 1);
		qDebug() << msg << "->" << buf;
	}
}
VideoReScaler::~VideoReScaler()
{
}
